package com.gljx.web.controller;

import com.gljx.util.*;
import com.gljx.web.Entity.*;
import com.gljx.web.dao.CoachtransferMapper;
import com.gljx.web.service.CarService;
import com.gljx.web.service.CustomLogService;
import com.gljx.web.service.DepartmentService;
import com.gljx.web.service.CoachtransferService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * Created by Administrator on 2017/11/20 0020.
 */
@Controller
@RequestMapping("/")
public class CoachTransferContraller {

    @Autowired
    CoachtransferService coachtransferService;
    @Autowired
    DepartmentService departmentService;
    @Autowired
    CustomLogService customLogService;
    @Autowired
    PersonController personController;
    @Autowired
    StudentController studentController;
    @Autowired
    CarService carService;
    @Autowired
    CoachtransferMapper coachtransferMapper;

    /**
     * @Author lcx
     * @Date 2017/12/13 0013 上午 9:18
     */
    @RequestMapping("/queryCoachTransfer/look.action")
    public String queryCoachTransfer(HttpServletRequest request, @RequestParam(value = "fnumber", defaultValue = "") String fnumber
            , @RequestParam(value = "cfcoachno", defaultValue = "") String cfcoachno
            , @RequestParam(value = "jlName", defaultValue = "") String jlName
            , @RequestParam(value = "beginTime", defaultValue = "") String beginTime
            , @RequestParam(value = "endTime", defaultValue = "") String endTime
            , @RequestParam(value = "state", defaultValue = "") String state
            , @RequestParam(value = "alertType", defaultValue = "") String alertType) {

        PageBean<Coachtransfer> pb = new PageBean<>();
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        try {
            fnumber = fnumber.trim();//去空格
            cfcoachno = cfcoachno.trim();
            jlName = jlName.trim();
            //第一次进来
            if ("first".equals(state)) {
                beginTime = TimeFormat.getMonth();
                endTime = TimeFormat.getNowTime();
                pb = getPageBean(request, user.getFcompanyid(), fnumber, cfcoachno, jlName, beginTime, endTime, "");
            } else if ("".equals(state) && "".equals(beginTime) || "".equals(endTime)) {
                pb = getPageBean(request, user.getFcompanyid(), fnumber, cfcoachno, jlName, beginTime, endTime, null);
            } else {
                pb = getPageBean(request, user.getFcompanyid(), fnumber, cfcoachno, jlName, beginTime, endTime, "");
            }
            //计数器
            int i = 0;
            //缓存需要删除的序列
            List<Integer> tem = new ArrayList<>();
            //获取当前分页的值
            List<Coachtransfer> coachtransferList = pb.getBeanList();
             /*合计信息条数*/
            String messageAmount="共有"+pb.getTr()+"条信息";
            //返回界面的搜索条件
            request.setAttribute("messageAmount",messageAmount);
            request.setAttribute("fnumber", fnumber);
            request.setAttribute("cfcoachno", cfcoachno);
            request.setAttribute("jlName", jlName);
            request.setAttribute("beginTime", beginTime);
            request.setAttribute("endTime", endTime);

            request.setAttribute("coachtransferList", coachtransferList);
            request.setAttribute("pb", pb);
            request.setAttribute("alertType", alertType);


        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return "/backHome/CoachManagement/Coachtransfer/CoachTransferList";
    }

    /**
     * @Author lcx
     * @Date 2017/12/13 0013 上午 9:18
     */
    public PageBean<Coachtransfer> getPageBean(HttpServletRequest request, String companyId, String fnumber,
                                               String cfcoachno, String jlName,
                                               String beginTime, String endTime,
                                               String state) throws Exception {

        int offset;//从第几条数据开始加载
        if (request.getParameter("pager.offset") == null) {
            offset = 0;
        } else {
            offset = Integer.parseInt(request.getParameter("pager.offset"));
        }
        //拼接SQL语句
        StringBuffer psql = new StringBuffer();
        if (state == null) {
            psql.append("SELECT " +
                    "  c.FID, " +
                    "  c.FNUMBER, " +
                    "  to_char(c.FBIZDATE, 'yyyy-mm-dd') fbizdate, " +
                    "  c.FDESCRIPTION, " +
                    "  u.NAME                            createName, " +
                    "  u2.NAME                           checkName, " +
                    "  p.FNAME_L2 jlName, " +
                    "  c2.CFCOACHNO, " +
                    "  a.FNAME_L2 carName, " +
                    "  a.FNUMBER cfcarno, " +
                    "  c2.CFREMARK, " +
                    "  c.CFBILLSTATE " +
                    "FROM CT_DS_COACHTRANSFER c LEFT JOIN CT_DS_COACHTRANSFERENTRY C2 ON c.FID = c2.FPARENTID " +
                    "  LEFT JOIN T_E_USER u ON c.FCREATORID = u.FID " +
                    "  LEFT JOIN T_E_USER u2 ON c.FAUDITORID = u2.fid " +
                    "  LEFT JOIN CT_DS_PERSON p ON c2.CFCOACHID = p.fid " +
                    "  LEFT JOIN CT_DS_CAR a on c2.CFCARID = a.FID");
            psql.append(" where c.FCONTROLUNITID= '" + companyId + "' ");
            if (!"".equals(jlName) && jlName != null) {
                psql.append("and p.FNAME_L2 LIKE '%" + jlName + "%' ");
            }
            if (!"".equals(cfcoachno) && cfcoachno != null) {
                psql.append(" AND c2.CFCOACHNO LIKE '%" + cfcoachno + "%' ");
            }
            psql.append(" ORDER BY c.FCREATETIME    DESC");
        } else {
            psql.append("SELECT " +
                    "  c.FID, " +
                    "  c.FNUMBER, " +
                    "  to_char(c.FBIZDATE, 'yyyy-mm-dd') fbizdate, " +
                    "  c.FDESCRIPTION, " +
                    "  u.NAME                            createName, " +
                    "  u2.NAME                           checkName, " +
                    "  p.FNAME_L2 jlName, " +
                    "  c2.CFCOACHNO, " +
                    "  a.FNAME_L2 carName, " +
                    "  a.FNUMBER cfcarno, " +
                    "  c2.CFREMARK, " +
                    "  c.CFBILLSTATE " +
                    "FROM CT_DS_COACHTRANSFER c LEFT JOIN CT_DS_COACHTRANSFERENTRY C2 ON c.FID = c2.FPARENTID " +
                    "  LEFT JOIN T_E_USER u ON c.FCREATORID = u.FID " +
                    "  LEFT JOIN T_E_USER u2 ON c.FAUDITORID = u2.fid " +
                    "  LEFT JOIN CT_DS_PERSON p ON c2.CFCOACHID = p.fid " +
                    "  LEFT JOIN CT_DS_CAR a on c2.CFCARID = a.FID");
            psql.append(" where c.FCONTROLUNITID= '" + companyId + "' ");
            if (!"".equals(jlName) && jlName != null) {
                psql.append("and p.FNAME_L2 LIKE '%" + jlName + "%' ");
            }
            if (!"".equals(cfcoachno) && cfcoachno != null) {
                psql.append(" AND c2.CFCOACHNO LIKE '%" + cfcoachno + "%' ");
            }
            psql.append(" AND (c.FBIZDATE BETWEEN to_date('" + beginTime + "', 'YYYY/MM/DD') AND to_date('" + endTime + "', 'YYYY/MM/DD'))" +
                    "  ORDER BY c.FCREATETIME    DESC");
        }

        int psize = 150; //每页显示数
        int pindex = offset / psize;//+1  页码从0开始
        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = coachtransferService.selectPage(pindex, psql.toString(), psize);
        PageBean<Coachtransfer> pb = new PageBean<>();
        pb.setPc(pindex); //页码
        Map<String, Object> paramMapCount = getPageBeanCount(psql.toString()); //取记录总数
        pb.setTr((int) paramMapCount.get("Pcount")); //记录总数
        pb.setPs(psize);
        pb.setBeanList((List<Coachtransfer>) paramMap.get("v_cur")); //每页数据集
        return pb;
    }

    /**
     * @Author lcx
     * @Date 2017/12/13 0013 上午 9:18
     */
    public Map<String, Object> getPageBeanCount(String psql) throws Exception {

        Map<String, Object> paramMap = new HashMap<String, Object>();
        paramMap = coachtransferService.selectPageCount(psql);
        return paramMap;
    }

    @RequestMapping(value = "/go_add_Coachtransfer")
    public String goAddCoachtransfer(HttpServletRequest request, String alertType) throws Exception {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        /*String number = customLogService.selectFunmber("CT_DS_COACHTRANSFER",user.getFcompanyid());*/
        String fnumber = GetFnumber.fnumbers("JLFC");

        //查询教练弹窗信息
        Map map1 = personController.getPageAsJl(request, "", "", "0");
        List<Car> cars = carService.queryCar(user.getFcompanyid());


        request.setAttribute("beginTime", TimeFormat.getMonth());
        request.setAttribute("endTime", TimeFormat.getNowTime());


        request.setAttribute("flag", "1");
        request.setAttribute("fbizdate", TimeFormat.getNowTime());
        request.setAttribute("createName", user.getName());
        request.setAttribute("fnumber", fnumber);
        request.setAttribute("department", department.getFnameL2());
        request.setAttribute("pb1", map1.get("pb"));
        request.setAttribute("persons", map1.get("sList"));
        request.setAttribute("time", TimeFormat.getNowTime());
        request.setAttribute("cars", cars);

        request.setAttribute("alertType", alertType);

        return "/backHome/CoachManagement/Coachtransfer/detailCoachTransferr";

    }

    @RequestMapping("/add_CoachTransfer")
    public String addCoachTransfer(HttpServletRequest request, Coachtransfer coachtransfer, @RequestParam(defaultValue = "0") String state) {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        //公司id
        coachtransfer.setCfficompanyid(user.getFcompanyid());
        //控制单元id
        coachtransfer.setFcontrolunitid(user.getFcompanyid());
        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //创建时间
        coachtransfer.setFcreatetime(createTime);
        //修改时间
        coachtransfer.setFcreatorid(user.getFid());


        //收集子类信息
        String[] cfcoachid = request.getParameterValues("cfcoachid");
        String[] cfcoachno = request.getParameterValues("cfcoachno");
        String[] cfcarid = request.getParameterValues("cfcarid");
        String[] cfcarno = request.getParameterValues("cfcarno");
        String[] cfremark = request.getParameterValues("cfremark");


        //添加练车  一个事物处理
        coachtransferService.addcoachtransfer(state, coachtransfer, cfcoachid, cfcoachno, cfcarid, cfcarno, cfremark);

        //添加日志
        customLogService.addLog("教练管理", TimeFormat.timeFormat(new Date()) + "教练分车新增", null, user.getFid());

        return "redirect:/DrivingSys/go_add_Coachtransfer?alertType=bc";
    }

    @RequestMapping(value = "go_update_CoachTransfer")
    public String goUpdateCoachTransfer(HttpServletRequest request, String fid, String xqid) throws Exception {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");
        Department department = departmentService.queryAdminByFid(user.getFcompanyid());

        //查询教练弹窗信息
        Map map1 = personController.getPageAsJl(request, "", "", "0");
        List<Car> cars = carService.queryCar(user.getFcompanyid());

        request.setAttribute("beginTime", TimeFormat.getMonth());
        request.setAttribute("endTime", TimeFormat.getNowTime());

        Coachtransfer coachtransfer = coachtransferService.selectCoachtransferByFid(fid);

        if (coachtransfer == null) {
            return "/error/not_data";
        }

        //查询是否是经办人
        Axamine axamine = new Axamine();
        request.setAttribute("AuditState", axamine.selectAuditPerson(coachtransfer.getFnumber()));

        request.setAttribute("flag", "2");
        request.setAttribute("fbizdate", TimeFormat.getNowTime());
        request.setAttribute("createName", user.getName());
        request.setAttribute("department", department.getFnameL2());
        request.setAttribute("pb1", map1.get("pb"));
        request.setAttribute("persons", map1.get("sList"));
        request.setAttribute("time", TimeFormat.getNowTime());
        request.setAttribute("coachtransfer", coachtransfer);
        request.setAttribute("cars", cars);

        return "/backHome/CoachManagement/Coachtransfer/detailCoachTransferr";
    }

    @RequestMapping(value = "/update_CoachTransfer")
    public String updateCoachTransfer(HttpServletRequest request, Coachtransfer coachtransfer) {

        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        //获取当前修改时间
        String createTime = TimeFormat.timeFormat(new Date());
        //修改时间
        coachtransfer.setFlastupdatetime(createTime);
        //修改人id
        coachtransfer.setFlastupdateuserid(user.getFid());

        addCoachTransfer(request, coachtransfer, "1");

        //添加日志
        customLogService.addLog("教练管理", TimeFormat.timeFormat(new Date()) + "对教练分车分车进行更新", null, user.getFid());

        return "redirect:/DrivingSys/queryCoachTransfer/look.action?state=first&alertType=qd";
    }

    @RequestMapping(value = "delete_CoachTransfer")
    public String deleteCoachtransfer(HttpServletRequest request, String[] deleteId, String[] fnumber) throws Exception {

        User user = (User) request.getSession().getAttribute("user");

        coachtransferService.deleteByCoachtransferKey(deleteId, fnumber);
        //添加日志
        customLogService.addLog("教练管理", TimeFormat.timeFormat(new Date()) + "对教练分车分车进行删除", null, user.getFid());


        return "redirect:/DrivingSys/queryCoachTransfer/look.action?state=first";
    }

    /**
     * @Author lcx
     * @Date 2018/2/6 0006 下午 1:43
     * 教练分车流程
     */
    @RequestMapping(value = "/queryCoachTransferExamine")
    @ResponseBody
    public ServerResponse examine(HttpServletRequest request, @RequestParam(defaultValue = "", value = "fid") String fid,
                                  @RequestParam(defaultValue = "", value = "state") String state,
                                  @RequestParam(defaultValue = "", value = "agreed") String agreed,
                                  @RequestParam(defaultValue = "", value = "auditcomment") String auditcomment,
                                  @RequestParam(defaultValue = "", value = "fnumber") String fnumber) {
        Coachtransfer coachtransfer = new Coachtransfer();

        coachtransfer.setFid(fid);
        coachtransfer.setFnumber(fnumber);

        return coachtransferService.examine(coachtransfer, state, agreed, auditcomment);
    }

    /**
     * @Author lcx
     * @Date 2018/2/27 0027 上午 11:49
     * 提交
     */
    @RequestMapping(value = "/queryCoachTransferSubmit")
    @ResponseBody
    public ServerResponse submit(HttpServletRequest request,
                                 @RequestParam(defaultValue = "", value = "fnumber") String fnumber,
                                 @RequestParam(defaultValue = "", value = "fid") String fid) {
        Axamine axamine = new Axamine();
        Coachtransfer coachtransfer = new Coachtransfer();

        coachtransfer.setFid(fid);
        /*coachtransfer.setFauditorid(((User) request.getSession().getAttribute("user")).getFid());*/
        coachtransfer.setCfbillstate(Long.valueOf("4"));
        coachtransferMapper.updateByPrimaryKeySelective(coachtransfer);
        return axamine.submissionProcess(String.valueOf(fnumber));
    }

    @RequestMapping("/queryCoachTransferXls")
    public String queryCoachTransferXls(HttpServletRequest request, HttpServletResponse response,
                                        @RequestParam(defaultValue = "", value = "jlName") String jlName,
                                        @RequestParam(defaultValue = "", value = "cfcoachno") String cfcoachno,
                                        @RequestParam(defaultValue = "", value = "beginTime") String beginTime,
                                        @RequestParam(defaultValue = "", value = "endTime") String endTime) {
        //获取操作人信息
        User user = (User) request.getSession().getAttribute("user");

        //头部数据
        List<Object> data = new ArrayList<>();
        String head[] = {"单据编号", "业务日期", "参考消息", "审核人名称", "制单人名称", "单据状态", "教练", "教练编码", "车辆", "车牌",
                "备注"
        };
        //长度
        Integer length[] = {8500, 5000, 6000, 3000, 3000, 3000, 3000, 3000, 6000, 3000,
                6000};

        List<Coachtransfer> coachtransferList = coachtransferService.selectCoachtransferAsXls(jlName, cfcoachno, beginTime, endTime, user.getFcompanyid());


        for (Coachtransfer coachtransfer : coachtransferList) {
            data.add(coachtransfer.getFnumber());
            data.add(coachtransfer.getFbizdate());
            data.add(coachtransfer.getFdescription());
            data.add(coachtransfer.getCheckName());
            data.add(coachtransfer.getCreateName());
            data.add(stateToString.billsState(coachtransfer.getCfbillstate()));
            data.add(coachtransfer.getJlName());//教练名称
            data.add(coachtransfer.getCfcoachno());
            data.add(coachtransfer.getCarName());//车辆
            data.add(coachtransfer.getCfcarno());//车牌
            data.add(coachtransfer.getCfremark());//备注
        }

        try {
            //导出Excel
            CommonExport.importExcel(response, "教练分车" + TimeFormat.getNowTime2() + ".xls", "教练分车", data, head, length);
        } catch (Exception e) {
            e.printStackTrace();
        }

        return "redirect:/DrivingSys/queryCoachTransfer/look.action?state=first";
    }

}
